package com.yami.shop.listener;

import com.yami.shop.bean.event.*;
import com.yami.shop.bean.model.MeltCloudGroup;
import com.yami.shop.dto.user.GroupNotificationMessageDTO;
import com.yami.shop.service.MeltCloudGroupService;
import com.yami.shop.service.impl.RongYunMsgServiceImpl;
import com.yami.shop.vo.advice.AdviceTxtVo;
import com.yami.shop.vo.message.message.PrivateMessageVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Collections;


/**
 * @Author lth
 * @Date 2021/11/12 9:26
 */
@Slf4j
@Component("sendSysMsgListener")
@AllArgsConstructor
public class SendSysMsgListener {

    private final RongYunMsgServiceImpl rongYunMsgServiceImpl;
    
    private final MeltCloudGroupService groupService;

    /**
     * 群聊
     */
    @Async
    @EventListener(MeltSendGroupSysMsgEvent.class)
    public void sendGroupSysMsgEvent(MeltSendGroupSysMsgEvent event) {
        GroupNotificationMessageDTO dto = new GroupNotificationMessageDTO();
        dto.setMessage(event.getMessage());
        dto.setObjectName(event.getObjectName());
        dto.setSenderId("0");
        dto.setOperatorUserId(event.getOperatorUserId());
        dto.setOperation(event.getOperation());
        dto.setTargetId(Collections.singletonList(event.getTargetId()));
        dto.setIsIncludeSender(event.getIsIncludeSender());
        dto.setExtra(event.getTExtra());
        dto.setToUserId(event.getToUserId());
        MeltCloudGroup group = groupService.getById(event.getTargetId());
        try {
            if (group.getType().equals("0")) {
                rongYunMsgServiceImpl.sendGroupAdvice(dto);
            } else {
                dto.setChannelId("RCDefault");
                rongYunMsgServiceImpl.sendUltraGroupAdvice(dto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 单聊
     * @param event
     */
    @Async
    @EventListener(MeltSendOneSysMsgEvent.class)
    public void sendOneSysMsgEvent(MeltSendOneSysMsgEvent event) {
        PrivateMessageVo privateMessageVo = new PrivateMessageVo();
        AdviceTxtVo adviceTxtVo = new AdviceTxtVo();
        adviceTxtVo.setContent(event.getMessage());
        adviceTxtVo.setExtra(event.getTExtra());
        privateMessageVo.setContent(adviceTxtVo);
        privateMessageVo.setObjectName(event.getObjectName());
        privateMessageVo.setSenderId(event.getSenderId());//系统
        privateMessageVo.setTargetId(Collections.singletonList(event.getTargetId()));
        privateMessageVo.setIsIncludeSender(event.getIsIncludeSender());
        try {
            rongYunMsgServiceImpl.privatePublishInfoNtf(privateMessageVo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
